<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Lbs Demo</title>
    <link rel="stylesheet" href="/static/js/jquery.svg.package-1.5.0/jquery.svg.css">
    <style>
        #myCanvas{width: 1500px; height: 800px;}
        #floor3 {width: 1450px; height: 750px;
            position: absolute;
            overflow: hidden;
            border: 2px solid #b94a48;}
        #svg_map{
            width: 1450px;
            height: 750px;
            position:absolute;
            overflow:hidden;
        }
        #svg_path{
            width: 1450px;
            height: 750px;
            position:absolute;
        }
    </style>
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/jquery.svg.package-1.5.0/jquery.svg.js"></script>
    <script src="/static/js/socket.io-1.3.5/socket.io.min.js"></script>

<script>
    'use strict';
var hzX = 0, hzY = 0;   // 坐标系原点
var margin = 0;
var real_loc_to_pix = 0.0891;
var map_w = 3477;       /// px
var map_h = 1769;
var zoom = 0.3;          /// 地图缩放级别
var hz_is_navigating = false;      /// 是否曾经设置过导航，或正在导航中
var HZ_DESTINATION_MEETING_ROOM = 27;
var hz_destination = HZ_DESTINATION_MEETING_ROOM;            /// 导航的目的地，默认 第一个 目的地
var hz_time_id = 0;
var hz_user_id = 0;
var HZ_USER_IDS = ['1918E00103AA', '1918E00103A9'];
var hz_user_xy = [];

var storage = window.localStorage;
if(storage){
    //storage.clear();
    ///alert("浏览支持localStorage");
    var _userId = storage['hz_user_id'];
    if(typeof _userId !== 'undefined') {
        hz_user_id = _userId;
    }
    var hz_zoom = storage['hz_zoom'];
    ///alert(hz_zoom);
    if(typeof hz_zoom !== 'undefined') {    /// 存在值
        zoom = hz_zoom;
    }

    var _dest = parseInt(storage['hz_destination']);
    isNaN(_dest) ? hz_destination = HZ_DESTINATION_MEETING_ROOM : hz_destination = _dest;

    ///alert(storage['hz_is_navigating'] + "  " + Boolean(storage['hz_is_navigating']));
    hz_is_navigating = Boolean(storage['hz_is_navigating']);
}else{
    ///alert("浏览暂不支持localStorage");
}

$(document).ready(function(){

    var namespace = '/HeZhong';

    // Connect to the Socket.IO server.
    // The connection URL has the following format:
    //     http[s]://<domain>:<port>[/<namespace>]
    var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);

    // Event handler for new connections.
    // The callback function is invoked when a connection with the
    // server is established.
    socket.on('connect', function() {
        socket.emit('hz_event', {data: "I'm connected!"});
        if (hz_is_navigating) {
            $('#go').click();
        }
    });

    // Event handler for server sent data.
    // The callback function is invoked whenever the server emits data
    // to the client. The data is then displayed in the "Received"
    // section of the page.
    socket.on('hz_response', function(msg) {
        /// $('#log').append('<br>' + $('<div/>').text('Received #' + msg.count + ': ' + msg.data).html());
    });

    socket.on('hz_position', function(msg) {
        console.log(msg);
        var json = eval(msg); // 数组
        $.each(json, function (index, item) {
            hz_user_xy[index] = [item['userId'], json[index]['x'], json[index]['y']];
        });

        for (var i = 0; i< hz_user_xy.length; i++) {
            hz_people_goto(hz_user_xy[i][1] * real_loc_to_pix * zoom - margin,
                    hz_user_xy[i][2] * real_loc_to_pix * zoom - margin, hz_user_xy[i][0]);
        }
    });

    socket.on('hz_path', function (msg) {
        console.log(msg);
        var pt_path = [];
        pt_path[0] = [msg.x * real_loc_to_pix * zoom, msg.y * real_loc_to_pix * zoom];
        var json = eval(msg.path); // 数组
        $.each(json, function (index, item) {
            // 循环获取数据
            pt_path[index+1] = [parseInt((json[index].x+44/2-2) * zoom), parseInt((json[index].y+44/2-2) * zoom)];
        });

        hz_people_go_no_animate(pt_path[pt_path.length-1][0], pt_path[pt_path.length-1][1], 'destination');
        $('#destination').show();

        var svg = $('#svg_path').svg('get');
        for ( var i = 0; i< pt_path.length; i++) {        // 转换坐标
            pt_path[i][0] += hzX;
            pt_path[i][1] += hzY;
        }
        svg.clear();
        svg.polyline(pt_path, {fill: 'none', stroke: 'blue', strokeWidth: 4});
    });

    $("#go").click(function(){
        $("#go").attr("disabled", true);
        $("#loc").attr("disabled", true);
        $("#userId").attr("disabled", true);

        storage['hz_is_navigating'] = true;
        hz_is_navigating = true;

        socket.emit('hz_navigating',
                {'location': hz_destination, 'userId':HZ_USER_IDS[hz_user_id-1] });

        /*
        // 未做错误处理。后续需要改正
        $.post("/go", {"location": hz_destination, "userId": HZ_USER_IDS[hz_user_id-1]}, function(data, status){
            var pt_path = [];
            var pt = eval(data.points); // 数组
            $.each(pt, function (index, item) {
                hz_people_goto(item['x'] * real_loc_to_pix * zoom + margin, item['y'] * real_loc_to_pix * zoom + margin, item['userId']);
                if (item['userId'] == HZ_USER_IDS[hz_user_id-1]) {
                    pt_path[0] = [item['x'] * real_loc_to_pix * zoom, item['y'] * real_loc_to_pix * zoom];
                }
            });

            var json = eval(data.path); // 数组
            $.each(json, function (index, item) {
                // 循环获取数据
                pt_path[index+1] = [parseInt((json[index].x+44/2-2) * zoom), parseInt((json[index].y+44/2-2) * zoom)];
            });

            hz_people_go_no_animate(pt_path[pt_path.length-1][0], pt_path[pt_path.length-1][1], 'destination');
            $('#destination').show();

            var svg = $('#svg_path').svg('get');
            svg.clear();
            for ( var i = 0; i< pt_path.length; i++) {        // 转换坐标
                pt_path[i][0] += hzX;
                pt_path[i][1] += hzY;
            }

            svg.polyline(pt_path, {fill: 'none', stroke: 'blue', strokeWidth: 4});

            storage['hz_is_navigating'] = true;
            hz_is_navigating = true;
        });
        */
     });

    /// 停止导航
    $("#stop").click(function () {
        if(hz_is_navigating){
            hz_clear_path();
            storage.removeItem('hz_is_navigating');
            hz_is_navigating = false;
            $("#go").attr("disabled", false);
            $("#loc").attr("disabled", false);
            $("#userId").attr("disabled", false);
            $("#destination").hide();

            socket.emit('hz_stop_navigating');
        }
    });

    $("#zoomOut").click(function () {
        zoom = parseFloat(zoom) + 0.05;
        storage['hz_zoom'] = zoom;
        hz_map_zoom(margin, margin, map_h * zoom, map_w * zoom);

        hz_change_item_in_map();
        /*
        for (var i = 0; i< hz_user_xy.length; i++) {
            hz_people_go_no_animate(hz_user_xy[i][1] * real_loc_to_pix * zoom - margin,
                    hz_user_xy[i][2] * real_loc_to_pix * zoom - margin, hz_user_xy[i][0]);
        }

        if (hz_is_navigating) {
            hz_clear_path();
            $("#go").click();
        }

        var svg = $('#svg_map').svg('get');
        svg.clear();
        drawInitial(svg);
        */
    });

    $("#zoomIn").click(function () {
        zoom = parseFloat(zoom) - 0.05;
        storage['hz_zoom'] = zoom;
        hz_map_zoom(margin, margin, map_h * zoom, map_w * zoom);

        hz_change_item_in_map();
        /*
        for (var i = 0; i< hz_user_xy.length; i++) {
            hz_people_go_no_animate(hz_user_xy[i][1] * real_loc_to_pix * zoom - margin,
                    hz_user_xy[i][2] * real_loc_to_pix * zoom - margin, hz_user_xy[i][0]);
        }

        if (hz_is_navigating) {
            hz_clear_path();
            $("#go").click();
        }

        var svg = $('#svg_map').svg('get');
        svg.clear();
        drawInitial(svg);
        */
    });
/*
    $(".btnGetLocation").click(function(){
        $.post("/get_location", {"userId": "1918E00103AA"}, function(data, status){
            var json = eval(data); // 数组
            $.each(json, function (index, item) {
                hz_user_xy[index] = [item['userId'], json[index]['x'], json[index]['y']];
            });

            for (var i = 0; i< hz_user_xy.length; i++) {
                hz_people_go_no_animate(hz_user_xy[i][1] * real_loc_to_pix * zoom - margin,
                        hz_user_xy[i][2] * real_loc_to_pix * zoom - margin, hz_user_xy[i][0]);
            }
        });
    });
*/
    /// 调整地图大小
    hz_map_zoom(margin, margin, map_h * zoom, map_w * zoom);

    if(hz_user_id != 0) {       /// 设置选择用户（标签）图片
        $('#'+ HZ_USER_IDS[hz_user_id-1]).attr('src', '/static/img/peoplesel.png');
    }
    /// 调整用户、标签位置
    ///$('.btnGetLocation').click();

    $("#loc").val(parseInt(hz_destination));
    $("#userId").val(parseInt(hz_user_id));
    $("#go").attr("disabled", hz_user_id == '0');
    $("#loc").attr("disabled", hz_user_id == '0');
    $('#destination').hide();

});

    function hz_change_item_in_map() {
        for (var i = 0; i< hz_user_xy.length; i++) {
            hz_people_go_no_animate(hz_user_xy[i][1] * real_loc_to_pix * zoom - margin,
                    hz_user_xy[i][2] * real_loc_to_pix * zoom - margin, hz_user_xy[i][0]);
        }

        if (hz_is_navigating) {
            hz_clear_path();
            $("#go").click();
        }

        var svg = $('#svg_map').svg('get');
        svg.clear();
        drawInitial(svg);
    }

function hz_map_zoom(left, top, height, width, isAnimate) {
    isAnimate = isAnimate || true;     // 默认参数为true，执行动画
    $("#map").stop(true, true).animate({
        left:left + hzX,
        top:top + hzY,
        height:height,
        width:width
    });
    if (!isAnimate) {
        $('#map').stop(true, true);
   }
}

function hz_people_goto(x, y, people) {
    people = people || '1918E00103AA';      // 设置默认参数
    /// 24, 45是定位图标的 针尖 位置。显示图片时，是以图片左上角为参考坐标。故需要对坐标进行偏移。
    $("#"+people).stop(true, true).animate({
        left: (hzX + x - 24),
        top: (hzY + y - 45)
    });
}

function hz_people_go_no_animate(x, y, people) {
    people = people || '1918E00103AA';      // 设置默认参数
    /// 24, 45 是定位图标的 针尖 位置。显示图片时，是以图片左上角为参考坐标。故需要对坐标进行偏移。
    $("#"+people).animate({
        left: hzX + x - 24,
        top: hzY + y - 45
    }).stop(true, true);
}

function hz_clear_path() {
    $('#svg_path').svg('get').clear();
}

$(function() {
	$('#svg_map').svg({onLoad: drawInitial});
    $('#svg_path').svg({onLoad: drawIniPath()});

    // pan map
    var hzStillDown = false;
    var hzCanvas = $("#floor3");
    var hzOriginalX = 0,  hzOriginalY = 0;
    hzCanvas.mousedown(function(event){
        // console.log('div floor3 was clicked!' + event.pageX + ',' + event.pageY);
        // console.log('offset:(' + event.offsetX + ',' + event.offsetY + ')');
        hzStillDown = true;
        hzOriginalX = event.offsetX;
        hzOriginalY = event.offsetY;
        $(this).css('cursor', 'move');
    });

    ///var hzCoords = [];
    hzCanvas.mousemove(function(e){
        ///if(!hzStillDown) return;
        // console.log("moving");
        ///hzCoords.push({x: e.offsetX, y: e.offsetY});
        // and/or do whatever you need with the coordinates
    });

    hzCanvas.mouseup(function(e){
        if (!hzStillDown) return;
        hzStillDown = false;
        $(this).css('cursor', 'default');
        if (e.offsetX - hzOriginalX == 0 && e.offsetY - hzOriginalY == 0) return;
        hzX += e.offsetX - hzOriginalX;
        hzY += e.offsetY - hzOriginalY;
        $('#map').animate({
            left: hzX,
            top: hzY
        });
        hz_change_item_in_map();
        /*
        var svg = $('#svg_map').svg('get');
        svg.clear();
        drawInitial(svg);
        */
    });
});

function drawIniPath() {
}

function drawInitial(svg) {
    var x_meeting_room = 1420;
    var y_meeting_room = 3000;
    svg.text(parseInt(x_meeting_room*real_loc_to_pix*zoom)+hzX, parseInt(y_meeting_room*real_loc_to_pix*zoom)+hzY, '会议室');
    transformDemo(svg);
}

function transformDemo(svg) {
    var x_meeting_room = 1420;
    var y_meeting_room = 4000;

    svg.describe('Example Skew - Show effects of skewX and skewY');
    var str3 = 'translate(' +  parseInt(x_meeting_room*real_loc_to_pix*zoom+hzX) + ',' + parseInt(y_meeting_room*real_loc_to_pix*zoom+hzY) + ')';
    var g1 = svg.group({transform: str3});
    var g2 = svg.group(g1, {transform: 'skewX(40)'});
    svg.text(g2, 0, 0, '会议室',
        {fontSize: 20, fontFamily: 'Verdana', fill: 'blue'});

    var y_manager1 = 8620;
    var str4 = 'translate(' +  parseInt(x_meeting_room*real_loc_to_pix*zoom+hzX) + ',' + parseInt(y_manager1*real_loc_to_pix*zoom+hzY) + ')';
    g1 = svg.group({transform: str4});
    g2 = svg.group(g1, {transform: 'skewY(30)'});
    svg.text(g2, 0, 0, '副总办公室1',
        {fontSize: 20, fontFamily: 'Verdana', fill: 'blue'});

    var x_storage = 20000;
    var y_storage = 5000;
    var str1 = 'translate(' +  parseInt(x_storage*real_loc_to_pix*zoom+hzX) + ',' + parseInt(y_storage*real_loc_to_pix*zoom+hzY) + ')';
    g1 = svg.group({transform: str1});
    svg.text(g1, 0, 0, '仓  库',
        {fontSize: 16, fontFamily: 'Verdana'});

    var str2 = 'translate(' +  parseInt(x_storage*real_loc_to_pix*zoom+hzX) + ',' + parseInt((y_storage+3000)*real_loc_to_pix*zoom+hzY) + ')';
    g1 = svg.group({transform: str2});
    g2 = svg.group(g1, {transform: 'rotate(-45)'});
    svg.text(g2, 0, 0, '前  台',
        {fontSize: 16, fontFamily: 'Verdana'});
}

var colours = ['purple', 'red', 'orange', 'yellow', 'lime', 'green', 'blue', 'navy', 'black'];

function random(range) {
	return Math.floor(Math.random() * range);
}

 /*
function getPos()
{
    if (hz_is_navigating) {
        $("#go").click();
    } else {
        ///$(".btnGetLocation").click();
    }

    for (var p in hz_user_xy) {
        if(hz_user_xy.hasOwnProperty(p)) {
            hz_people_goto(hz_user_xy[p][0] * real_loc_to_pix * zoom - margin,
                    hz_user_xy[p][1] * real_loc_to_pix * zoom - margin, p );
        }
    }
}
*/

/// hz_time_id = window.setInterval("getPos()", 1000);

function selectLocation(str){
    hz_destination = parseInt(str);
    storage['hz_destination'] = hz_destination;
}

function selectUser(str){
    if(hz_user_id != 0) {       /// 还原用户（标签）图片为“未选中”状态
        $('#'+ HZ_USER_IDS[hz_user_id-1]).attr('src', '/static/img/people.png');
    }
    hz_user_id = str;
    storage['hz_user_id'] = hz_user_id;
    if(hz_user_id != 0) {       /// 设置选择用户（标签）图片
        $('#'+ HZ_USER_IDS[hz_user_id-1]).attr('src', '/static/img/peoplesel.png');
    }

    $("#go").attr("disabled", hz_user_id == '0');
    $("#loc").attr("disabled", hz_user_id == '0');
}

</script>

    <link rel="shortcut icon" href="/static/img/favicon.ico" />
    <link rel="bookmark" href="/static/img/favicon.ico" type="image/x-icon" />

</head>
<body>

<p id="top_panel"><a href="http://www.hezhongsz.com/"><img src="/static/img/hzlogo.png"></a>Floor3平面图
<a href="/">主页</a>

<div id="txtHint">
    <select id="userId" onchange="selectUser(this.value)" style="font-family:Verdana, Arial, Helvetica, sans-serif;">
        <option value="0">请选择用户开启导航</option>
        <option value="1">1918E00103AA</option>
        <option value="2">1918E00103A9</option>
    </select>
    导航到
    <select id="loc" class="loc" name="locations" onchange="selectLocation(this.value)" style="font-family:Verdana, Arial, Helvetica, sans-serif;">
        <option value="27">Room 1 测试区</option>
        <option value="29">Room 2</option>
        <option value="30">Room 3</option>
        <option value="31">Room 4 健身房</option>
        <option value="32">Room 5</option>
        <option value="33">Room 6</option>
        <option value="34">Room 7 演示厅</option>
        <option value="23">会议室</option>
        <option value="28">总裁办公室</option>
        <option value="24">副总办公室1</option>
        <option value="25">副总办公室2</option>
        <option value="26">仓库</option>
    </select>
    <button class="navigation" id="go">开始导航</button>
    <button id="stop">结束导航</button>
    <button id="myPosition" style="visibility:hidden">占位</button>地图：
    <button id="zoomOut">放大</button>
    <button id="zoomIn">缩小</button>
</div>
</p>

<div id="myCanvas">
    <div id="floor3">
        <img src="/static/img/floor3.svg" width="1043.1" height="530.7" style="position:absolute" id="map" >
        <div id="svg_map">
            <div id="svg_path"></div>
            <img src="/static/img/people.png" style="position:absolute" id="1918E00103AA" title="1918E00103AA">
            <img src="/static/img/people.png" style="position:absolute" id="1918E00103A9" title="1918E00103A9">
            <img src="/static/img/dest.png" style="position:absolute" id="destination" title="终点">
        </div>
    </div>
</div>

<!--
<h2>Receive:</h2>
<div id="log"></div>
-->

<!--
<button class="btnGetLocation" style="background-color:#666666;display:none">11. send userId to flask</button><br>
-->
</body>
</html>
